const { Category, Course } = require("../../models");
const { Op } = require("sequelize");
const { NotFoundError } = require("../../utils/errors");
const { paging } = require("../../utils/utils");

/**
 * 获取分页列表
 * @param req
 * @returns {Promise<{rows: Model[], count: number}>}
 */
exports.list = async (req) => {
  try {
    // 获取分页参数
    const { query, currentPage, pageSize, offset } = paging(req);
    const condition = {
      order: [
        ["rank", "ASC"],
        ["id", "ASC"],
      ],
      limit: pageSize,
      offset: offset,
    };

    if (query.name) {
      condition.where = {
        name: {
          [Op.like]: `%${query.name}%`,
        },
      };
    }
    // 分页查询
    const { rows, count } = await Category.findAndCountAll(condition);
    return { rows, count, currentPage, pageSize };
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 获取所有分类
 * @param req
 * @returns {Promise<Model[]>}
 */
exports.all = async (req) => {
  try {
    const condition = {
      order: [
        ["rank", "ASC"],
        ["id", "ASC"],
      ],
      include: [
        {
          model: Course,
          as: "courses",
          attributes: ["id", "name"],
        },
      ],
    };

    if (req.query.name) {
      condition.where = {
        name: {
          [Op.like]: `%${req.query.name}%`,
        },
      };
    }
    return await Category.findAll(condition);
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 获取分类详情
 * @param id
 * @returns {Promise<Model<*, TModelAttributes>>}
 */
exports.details = async (id) => {
  try {
    return await this.getById(id);
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 创建分类
 * @param body
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
exports.create = async (body) => {
  try {
    return await Category.create(body);
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 删除分类
 * @param id
 * @returns {Promise<void>}
 */
exports.del = async (id) => {
  try {
    const category = await this.getById(id);
    const count = await Course.count({
      where: { categoryId: id },
    });
    if (count > 0) {
      throw new Error("当前分类有课程，无法删除。");
    }
    await category.destroy();
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 更新分类
 * @param id
 * @param body
 * @returns {Promise<Model<*, TModelAttributes>>}
 */
exports.update = async (id, body) => {
  try {
    const category = await this.getById(id);
    await category.update(body); //删除
    return category;
  } catch (error) {
    throw new Error(error);
  }
};

/**
 * 根据id获取分类
 * @param id
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
exports.getById = async (id) => {
  // 获取当前分类
  const category = await Category.findByPk(id);
  if (!category) {
    throw new NotFoundError(`ID: ${id} not found`);
  }
  return category;
};
